import { login as apiLogin, getUserProfile } from '@/utils/api';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { useRouter } from 'expo-router';
import React, { useContext, useState } from 'react';
import { Alert, StyleSheet, Text, TextInput, TouchableOpacity, View } from 'react-native';
import { AuthContext } from './_layout';

export default function LoginScreen() {
  const [username, setUsername] = useState('admin');
  const [password, setPassword] = useState('admin123');
  const router = useRouter();
  const { setIsLogin } = useContext(AuthContext);

  const handleLogin = async () => {
    if (!username) {
      Alert.alert('提示', '请输入您的账号');
      return;
    }
    if (!password) {
      Alert.alert('提示', '请输入您的密码');
      return;
    }
    try {
      const res = await apiLogin(username, password, "");
      if (res.code === 0 && res.data) {
        await AsyncStorage.setItem('ACCESS_TOKEN', res.data.accessToken);
        await AsyncStorage.setItem('REFRESH_TOKEN', res.data.refreshToken);
        const info  = await getUserProfile(res.data.accessToken);
        console.log(info.data)
        await AsyncStorage.setItem('NICK_NAME', info.data.nickname);
        await AsyncStorage.setItem('USER_NAME', info.data.username);
        await AsyncStorage.setItem('USER', JSON.stringify(info.data));
        await AsyncStorage.setItem('TEST_USER', JSON.stringify(info.data));
        
        // 更新登录状态
        setIsLogin(true);
        // 跳转到模式选择页面，而不是直接跳转到首页
        router.replace('/mode-selection');
      } else {
        Alert.alert('登录失败', res.msg || '账号或密码错误');
      }
    } catch (e: any) {
      Alert.alert('网络错误', e.message || '请检查网络');
    }
  };

  const handleOpenAgreement = (type: 'user' | 'privacy') => {
    // TODO: 替换为实际协议链接
    // const url = type === 'user'
    //   ? 'https://yourdomain.com/user-agreement'
    //   : 'https://yourdomain.com/privacy-policy';
    // Linking.openURL(url);
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>安捷星</Text>
      <View style={styles.inputContainer}>
        <TextInput
          style={styles.input}
          placeholder="请输入账号"
          value={username}
          onChangeText={setUsername}
        />
        <TextInput
          style={styles.input}
          placeholder="请输入密码"
          value={password}
          onChangeText={setPassword}
          secureTextEntry
        />
      </View>
      <TouchableOpacity style={styles.loginButton} onPress={handleLogin}>
        <Text style={styles.loginButtonText}>登录</Text>
      </TouchableOpacity>
      <View style={styles.agreementContainer}>
        <Text>登录即代表同意</Text>
        <TouchableOpacity onPress={() => handleOpenAgreement('user')}>
          <Text style={styles.agreementText}>《用户协议》</Text>
        </TouchableOpacity>
        <TouchableOpacity onPress={() => handleOpenAgreement('privacy')}>
          <Text style={styles.agreementText}>《隐私协议》</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#fff' },
  title: { fontSize: 32, fontWeight: 'bold', marginBottom: 40, color: '#0a7ea4' },
  inputContainer: { width: '80%', marginBottom: 30 },
  input: { backgroundColor: '#f5f6f7', borderRadius: 20, padding: 12, marginBottom: 16, fontSize: 16 },
  loginButton: { backgroundColor: '#0a7ea4', borderRadius: 20, paddingVertical: 12, width: '80%', alignItems: 'center' },
  loginButtonText: { color: '#fff', fontSize: 18, fontWeight: 'bold' },
  agreementContainer: { flexDirection: 'row', marginTop: 24, alignItems: 'center' },
  agreementText: { color: '#0a7ea4', marginLeft: 4, marginRight: 4 },
}); 